import { defineStore } from "pinia";
import { userLogin, userlist } from "@/api/index";
import router from "@/router";
import { ElMessage } from "element-plus";
import { ref } from "vue";

const storeSetup = () => {
  const token = ref("");
  const UserListData = ref<{ items: Array<unknown>; total: number }>(null);
  // 登录
  const Login = async (username: string, password: string) => {
    let result = await userLogin({ username, password });
    if (result.code == 20000) {
      token.value = result.data.token;
      ElMessage.success("登录成功");
      router.push("/");
    } else if (result.message) {
      ElMessage.error(result.message);
    } else {
      ElMessage.error("用户不存在或者密码错误!");
    }
  };
  // 获取用户列表
  const UserList = async (page: number, limit: number, username: object) => {
    let result = await userlist({ page, limit, username });
    if (result.code == 20000) {
      UserListData.value = result.data;
    } else {
      ElMessage.error("获取用户列表失败!");
    }
  }; 
  return { token, UserListData, Login, UserList };
};

export const useloginStore = defineStore("login", storeSetup, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'token',//设置存储的key
        /* storage: localStorage,//表示存储在localStorage
        paths: token,//指定要长久化的字段 */
        storage: sessionStorage,
        paths: ['token']
      }
    ]
  }
});
